package com.github.bridge.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.github.bridge.domain.SysConfig;
import com.github.bridge.service.WeightConfigService;
import com.github.bridge.util.Const;
import com.github.bridge.util.R;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import wiki.xsx.core.handler.HashHandler;
import wiki.xsx.core.util.RedisUtil;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/weight")
@RequiredArgsConstructor
@Tag(name = "配置相关")
@Hidden
public class WeightConfigController {
    private final WeightConfigService weightConfigService;

    @SaIgnore
    @GetMapping("/configList")
    public R<List<SysConfig>> configList() {
        List<SysConfig> list = weightConfigService.list();
        return R.ok(list);
    }

    @SaIgnore
    @PostMapping("/saveConfig")
    public R<?> saveConfig(@RequestBody Map<String, Object> business) {
        String systemId = business.get("systemId").toString();
        SysConfig one = weightConfigService.findBySystemId(systemId);
        if (one != null) {
            throw new RuntimeException("业务id已存在");
        }
        SysConfig weightConfig = new SysConfig();
        weightConfig.setSystemId(systemId);
        weightConfig.setSystemName(business.get("systemName").toString());
        weightConfig.setWeight(Integer.parseInt(business.get("weight").toString()));
        weightConfigService.save(weightConfig);
        return R.ok();
    }

    @SaIgnore
    @PutMapping("/config/{id}")
    public void updateConfig(@PathVariable("id") Integer id, @RequestBody Map<String, Object> updatedBusiness) {
        SysConfig weightConfig = new SysConfig();
        weightConfig.setId(id);
        weightConfig.setWeight(Integer.parseInt(updatedBusiness.get("weight").toString()));
        weightConfigService.updateById(weightConfig);

        updateRedis(id);
    }

    @SaIgnore
    @DeleteMapping("/config/{id}")
    public void deleteBusiness(@PathVariable("id") Integer id) {
        weightConfigService.removeById(id);

        updateRedis(id);
    }

    public void updateRedis(Integer id) {
        SysConfig sysConfig = weightConfigService.getById(id);
        if (sysConfig != null) {
            HashHandler hashHandler = RedisUtil.getHashHandler();
            hashHandler.remove(Const.SYSTEM_CONFIG_KEY, sysConfig.getSystemId());
        }
    }

}
